import axios from 'axios';

const API_BASE_URL = 'http://localhost:8080';

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,  // 从5000ms增加到30000ms
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  }
});
// 获取所有订单列表
export const getAllOrders = async (params) => {
  try {
    const response = await api.get('/order/page', { params });
    return response.data;
  } catch (error) {
    console.error('获取订单列表失败:', error);
    throw new Error('获取订单列表失败');
  }
};

// 获取订单详情
export const getOrderById = async (number) => {
  try {
    const response = await api.get(`/order/detail/${number}`);
    return response.data;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    throw new Error('获取订单详情失败');
  }
};

// 更新订单状态
export const updateOrderStatus = async (number, status) => {
  try {
    const response = await api.put(`/order/status/${number}`, { status });
    return response.data;
  } catch (error) {
    console.error('更新订单状态失败:', error);
    throw new Error('更新订单状态失败');
  }
};

// 删除订单
export const deleteOrder = async (number) => {
  try {
    const response = await api.delete(`/order/delete/${number}`);
    return response.data;
  } catch (error) {
    console.error('删除订单失败:', error);
    throw new Error('删除订单失败');
  }
};

// 更新商品信息
export const updateProduct = async (productData) => {
  try {
    const response = await api.put(`/product/update`, productData);
    return response.data;
  } catch (error) {
    console.error('更新商品失败:', error);
    throw new Error('更新商品失败');
  }
};

// 删除商品
export const deleteProduct = async (id) => {
  try {
    const response = await api.delete(`/product/delete/${id}`);
    return response.data;
  } catch (error) {
    console.error('删除商品失败:', error);
    throw new Error('删除商品失败');
  }
};

//根据商品id获取商品
export const getProductById = async (id) => {
  try {
    const response = await api.get(`/product/detail/${id}`);
    return response.data;
  } catch (error) {
    console.error('获取商品详情失败:', error);
    throw new Error('获取商品详情失败');
  }
};

//添加商品
export const addProduct = async (productData) => {
  try {
    const response = await api.post('/product/add', productData);
    return response.data;
  } catch (error) {
    throw new Error('添加商品失败');
  }
};

//员工登录
export const employeeLogin = async ({ username, password }) => {
  try {
    const response = await api.post('/employee/login', { username, password });
    return response.data;
  } catch (error) {
    throw new Error('登录失败，请检查用户名和密码');
  }
};


// 添加商品评论
export const addReview = async (reviewData) => {
  try {
    const response = await api.post('/product/apprasie', reviewData);
    return response.data;
  } catch (error) {
    throw new Error('添加评论失败');
  }
};

//获取商品评论
export const getProductReviews = async (productId) => {
  try {
    const response = await api.get(`/product/apprasielist/${productId}`);
    return response.data;
  } catch (error) {
    throw new Error('获取评论失败');
  }
};

// 获取商品数据
export const product = async () => {
  const response = await api.get('/product/list');
  return response.data;
};

// 获取商品数据并加上分页查询
export const productWithPagination = async (params) => {
  const { page, pageSize, query } = params;

  // 使用标准查询参数格式
  const response = await api.get('/product/pagelist', {
    params: {
      page,      // 页码
      pageSize,  // 每页条数
      query: query || ''  // 如果查询条件为空，则传递空字符串
    }
  });

  return response.data;
};


// 用户登录
export const login = async ({ username, password }) => {
  try {
    const response = await api.post('/user/login', { username, password });
    return response.data;
  } catch (error) {
    throw new Error('登录失败，请检查用户名和密码');
  }
};

// 用户注册
export const register = async ({ username, password }) => {
  try {
    await api.post('/user/register', { username, password });
    return response.data;
  } catch (error) {
    throw new Error('注册失败，请检查用户名和密码');
  }
};

//用户退出
export const out = async () => {
  const response = await api.get('/user/out')
  return response.data;
}

// 文件上传
// 文件上传
export const uploadFile = async (file) => {
  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await api.post('/files/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 30000  // 增加超时时间到30秒
    });
    return response.data;
  } catch (error) {
    console.error('文件上传失败:', error);
    throw new Error('文件上传失败');
  }
};

// 购物车相关API

// 获取购物车列表
export const getCartItems = async (data) => {
  const response = await api.get('/cart/list', {
    params: data
  });
  return response.data;
}

// 添加商品到购物车
export const addToCart = async (data) => {
  return api.post('/cart/add', data);
}

// 更新购物车商品数量
export const updateCartItem = async (id, quantity) => {
  const response = await api.put(`/cart/update/${id}?quantity=${quantity}`);
  return response.data;
}

// 删除购物车商品
export const removeCartItem = async (id) => {
  return api.delete(`/cart/delete/${id}`);
}

// 清空购物车
export const clearCart = async (userId) => {
  return api.delete(`/cart/clear/${userId}`);
}

// 订单相关API
// 创建订单
export const createOrder = async (data) => {
  try {
    const response = await api.post('/order/create', data);
    return response.data;
  } catch (error) {
    console.error('创建订单失败:', error);
    throw new Error('创建订单失败');
  }
}

// 支付订单
export const payOrder = async (orderNumber, paymentMethod) => {
  try {
    const response = await api.put(`/order/${orderNumber}/pay`, { paymentMethod });
    return response.data;
  } catch (error) {
    console.error('支付订单失败:', error);
    throw new Error('支付订单失败');
  }
}

// 获取仪表盘统计数据
export const getDashboardStatistics = async (days = 30) => {
  try {
    const response = await api.get('/statistics/dashboard', { params: { days } });
    return response.data;
  } catch (error) {
    console.error('获取统计数据失败:', error);
    throw new Error('获取统计数据失败');
  }
};

// 获取商品销售排行
export const getProductRanking = async (timeRange = 'month') => {
  try {
    const response = await api.get('/statistics/product-ranking', { params: { timeRange } });
    return response.data;
  } catch (error) {
    console.error('获取商品销售排行失败:', error);
    throw new Error('获取商品销售排行失败');
  }
};

// 文化资讯相关API

// 获取文化资讯列表（分页）
export const getCulturalInfoWithPagination = async (params) => {
  const { page, pageSize, query } = params;
  const response = await api.get('/cultural-info/pagelist', {
    params: {
      page,
      pageSize,
      query: query || ''
    }
  });
  return response.data;
};

// 添加文化资讯
export const addCulturalInfo = async (infoData) => {
  try {
    const response = await api.post('/cultural-info/add', infoData);
    return response.data;
  } catch (error) {
    throw new Error('添加文化资讯失败');
  }
};

// 根据ID获取文化资讯详情
export const getCulturalInfoById = async (id) => {
  try {
    const response = await api.get(`/cultural-info/detail/${id}`);
    return response.data;
  } catch (error) {
    console.error('获取文化资讯详情失败:', error);
    throw new Error('获取文化资讯详情失败');
  }
};

// 更新文化资讯
export const updateCulturalInfo = async (infoData) => {
  try {
    const response = await api.put('/cultural-info/update', infoData);
    return response.data;
  } catch (error) {
    console.error('更新文化资讯失败:', error);
    throw new Error('更新文化资讯失败');
  }
};

// 删除文化资讯
export const deleteCulturalInfo = async (id) => {
  try {
    const response = await api.delete(`/cultural-info/delete/${id}`);
    return response.data;
  } catch (error) {
    console.error('删除文化资讯失败:', error);
    throw new Error('删除文化资讯失败');
  }
};

// 获取商品评价列表（分页）
export const getProductAppraises = async (params) => {
  const response = await api.get('/product/appraises', { params });
  return response.data;
}

// 删除商品评价
export function deleteProductAppraise(id) {
  return request({
    url: `/product/appraise/${id}`,
    method: 'delete'
  });
}

export default {
  product,
  login,
  register,
  uploadFile,
  getProductReviews,
  addReview,
  out,
  employeeLogin,
  productWithPagination,
  addProduct,
  getProductById,
  updateProduct,
  deleteProduct,
  getAllOrders,
  getOrderById,
  updateOrderStatus,
  deleteOrder,
  getCartItems,
  addToCart,
  updateCartItem,
  removeCartItem,
  clearCart,
  createOrder,
  payOrder,
  getCulturalInfoWithPagination,
  addCulturalInfo,
  getCulturalInfoById,
  updateCulturalInfo,
  deleteCulturalInfo
};
